using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.productpurchaseprices;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.productpurchaseprices
{
    /// <summary>
    /// 修改商品采购价格命令处理器
    /// </summary>
    public class UpdateProductPurchasePriceCommandHandler : IRequestHandler<UpdateProductPurchasePriceCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<ProductPurchasePrice> _productPurchasePriceRepository;

        private readonly IMapper _mapper;
        private readonly ILogger<UpdateProductPurchasePriceCommandHandler> _logger;

        public UpdateProductPurchasePriceCommandHandler(
            IBaseRepository<ProductPurchasePrice> productPurchasePriceRepository,

            IMapper mapper,
            ILogger<UpdateProductPurchasePriceCommandHandler> logger)
        {
            _productPurchasePriceRepository = productPurchasePriceRepository;

            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改商品采购价格命令
        /// </summary>
        /// <param name="request">修改商品采购价格命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateProductPurchasePriceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证商品采购价格是否存在
                var existingPrice =  _productPurchasePriceRepository.GetAll()
                    .FirstOrDefault(p => p.Id == request.Id && !p.IsDeleted);

                if (existingPrice == null)
                {
                    return ApiResult<bool>.Error("商品采购价格不存在");
                }

                
                // 验证日期范围
                if (request.StartDate >= request.EndDate)
                {
                    return ApiResult<bool>.Error("开始日期必须早于结束日期");
                }

                // 验证同一供应商下是否存在相同商品名称和规格的其他价格记录（排除当前记录）
                var duplicatePrice = await _productPurchasePriceRepository.GetAll()
                    .FirstOrDefaultAsync(p =>
                        p.Id != request.Id &&
                        p.SupplierId == request.SupplierId &&
                        p.ProductName == request.ProductName &&
                        p.Specification == request.Specification &&
                        !p.IsDeleted, cancellationToken);

                if (duplicatePrice != null)
                {
                    return ApiResult<bool>.Error("该供应商下已存在相同商品名称和规格的价格记录");
                }

                // 手动更新实体属性，避免导航属性问题
                existingPrice.SupplierId = request.SupplierId;
                existingPrice.ProductName = request.ProductName;
                existingPrice.Specification = request.Specification;
                existingPrice.MeasurementUnit = request.MeasurementUnit;
                existingPrice.InvoicePrice = request.InvoicePrice;
                existingPrice.SettlementPrice = request.SettlementPrice;
                existingPrice.Discount = request.Discount;
                existingPrice.PublicPrice = request.PublicPrice;
                existingPrice.StartDate = request.StartDate;
                existingPrice.EndDate = request.EndDate;
                existingPrice.SchemeName = request.SchemeName;
                existingPrice.Remarks = request.Remarks;

                // 设置更新时间
                existingPrice.UpdatedTime = DateTime.Now;

                // 更新商品采购价格
                var result = await _productPurchasePriceRepository.UpdateAsync(existingPrice);

                if (result > 0)
                {
                 
                    return ApiResult<bool>.Success(true, "商品采购价格修改成功");
                }
                else
                {
           

                    return ApiResult<bool>.Error("商品采购价格修改失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改商品采购价格时发生异常，ID: {PriceId}, 供应商ID: {SupplierId}, 商品: {ProductName}",
                    request.Id, request.SupplierId, request.ProductName);

                return ApiResult<bool>.Error("修改商品采购价格时发生异常");
            }
        }
    }
}